package com.example.afinal.offlineupdate.update;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Final on 22/11/2017.
 */

public class UpdateActivity extends AppCompatActivity {

    public static final int CHECK_LOCAL_UPDATE = 0X01;
    public static final int CHECK_NET_UPDATE = 0X02;
    public static final int CHECK_UPDATE_MSG = 0X03;
    ProgressBar progressBar;
    private String apk;
    private String description;
    AlertDialog updateMsgDialog;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(layoutParams);
        setContentView(layout);
        progressBar = new ProgressBar(this);
        layout.addView(progressBar);

        updateMsgDialog = new AlertDialog.Builder(this).create();
        updateMsgDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });

        Intent intent = getIntent();
        int action = intent.getIntExtra("action", CHECK_UPDATE_MSG);
        apk = intent.getStringExtra("apk");
        description = intent.getStringExtra("description");

        switch (action){
            case CHECK_LOCAL_UPDATE:
                executorService.execute(localUpdateRunnable);
                break;
            case CHECK_NET_UPDATE:
                executorService.execute(netUpdateRunnable);
                break;
            case CHECK_UPDATE_MSG:
                progressBar.setVisibility(View.GONE);
                showUpdateMsgDialog(apk, description);
                break;
            default:
                finish();
                break;
        }

    }

    /**
     * 通过SD卡，U盘更新
     */
    private Runnable localUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            File apkFile = ApkUpdateUtils.getInstance().findUpdatePackage(UpdateActivity.this, Environment.getExternalStorageDirectory().getAbsolutePath());
            if(apkFile == null){
                apkFile = ApkUpdateUtils.getInstance().findUpdatePackage(UpdateActivity.this, "/storage/extsd");
            }
            if(apkFile == null){
                apkFile = ApkUpdateUtils.getInstance().findUpdatePackage(UpdateActivity.this, "/storage/usbhost1");
            }
            if(apkFile == null){
                apkFile = ApkUpdateUtils.getInstance().findUpdatePackage(UpdateActivity.this, "/storage/usbhost2");
            }
            if(apkFile == null){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateActivity.this, "未发现新版本", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }else{
                apk = apkFile.getAbsolutePath();
                File msg = new File(apkFile.getParent(), apkFile.getName().replace(".apk", ".txt"));
                description = ApkUpdateUtils.getInstance().readStringFile(msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        showUpdateMsgDialog(apk, description);
                    }
                });
            }
        }
    };

    private Runnable netUpdateRunnable = new Runnable() {
        @Override
        public void run() {

        }
    };

    /**
     * 显示更新提示对话框
     */
    private void showUpdateMsgDialog(final String apk, String descrption){
        PackageInfo apkInfo = getPackageManager().getPackageArchiveInfo(apk, 0);
        updateMsgDialog.setTitle("检测到新版本"+apkInfo.versionName);
        updateMsgDialog.setMessage(descrption);
        updateMsgDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        updateMsgDialog.setButton(AlertDialog.BUTTON_POSITIVE, "安装", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ApkUpdateUtils.getInstance().silentInstall(UpdateActivity.this, apk);
            }
        });
        updateMsgDialog.show();
    }

}
